async function run() {
  showOverlay();

  let shipments = await getShipments();
  let delShipmentIds = await getDeleteShipments();

  chrome.runtime.sendMessage({ action: 'openUrlAndExecScript', data: { shipments, delShipmentIds } });
}

async function getShipments() {
  let url = location.origin + '/fba/shippingqueue/api/v1/shipment/listShipments?pageSize=101&&&orderBy=SHIPMENT_CREATE_DATE&isOrderAscending=false&&t2pLaunched=true';

  try {
    let response = await fetch(url);
    let list = await response.json();

    let items = list.filter((item) => {
      return isNeedSave(item);
    }).map((item) => {
      return {
        createdDate: convertToBeijingTime(item.createdDate),
        expectedQuantity: item.expectedQuantity,
        mskus: item.mskus,
        shipmentId: item.shipmentId,
        shipmentStatus: item.shipmentStatus
      };
    });

    return items;
  } catch (error) {
    console.error('Error fetching shipments:', error);
    return [];
  }
}

async function getDeleteShipments() {
  let url = location.origin + '/fba/shippingqueue/api/v1/shipment/listShipments?pageSize=101&&detailedShipmentStatuses=CANCELLED&detailedShipmentStatuses=DELETED&&orderBy=SHIPMENT_UPDATE_DATE&isOrderAscending=false&&t2pLaunched=true';

  try {
    let response = await fetch(url);
    let list = await response.json();

    let items = list.filter((item) => item.shipmentId).map((item) => item.shipmentId);

    return items;
  } catch (error) {
    console.error('Error fetching delete shipments:', error);
    return [];
  }
}

function isNeedSave(item) {
  if (['CANCELLED', 'DELETED'].includes(item.shipmentStatus))
    return false;
  else if (item.receivedQuantity == 0 && item.shipmentStatus == 'CLOSED')
    return false;
  else
    return true;
}

function convertToBeijingTime(timestamp) {
  if (!timestamp || isNaN(timestamp)) {
    return timestamp;
  }

  var date = new Date(timestamp);
  date.setHours(date.getHours() + 8);

  var year = date.getFullYear();
  var month = date.getMonth() + 1; // getMonth() 返回 0-11
  var day = date.getDate();

  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  return year + '-' + month + '-' + day;
}

run()
